﻿using ApplicationBase.Core.Logs;
using MediatR;
using Microsoft.Extensions.Logging;
using System.Diagnostics;
using System.Text.Json;

namespace IdentityService.Application.Behaviours
{
    public class LoggerBehaviour<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse> where TRequest : IRequest<TResponse>
    {
        private readonly ILogger<TRequest> _logger;
        public LoggerBehaviour(ILogger<TRequest> logger)
            => _logger = logger;

        public async Task<TResponse> Handle(TRequest request, RequestHandlerDelegate<TResponse> next, CancellationToken cancellationToken)
        {
            var requestJson = JsonSerializer.Serialize(request);
            _logger.LogInformation($"[Start Command] {typeof(TRequest).Name} - {requestJson}");

            Stopwatch watch = Stopwatch.StartNew();
            var response = await next();
            watch.Stop();

            var responseJson = JsonSerializer.Serialize(response);
            _logger.LogInformation($"[End Command] {typeof(TRequest).Name} - {responseJson}");

            var logModel = new UnitOfWorkLog(typeof(TRequest).Name, watch.ElapsedMilliseconds, DateTime.Now);
            _logger.LogInformation($"<UOW>{logModel.ToJson()}</UOW>");

            return response;
        }
    }
}
